package com.android.lovely.framework.widget

import android.content.Context
import android.util.AttributeSet
import android.widget.FrameLayout
import com.android.lovely.R
import com.android.lovely.databinding.LayoutTitleBarBinding
import com.android.lovely.databinding.ViewNoContentBinding
import com.android.lovely.ext.getActivity
import com.kotlin.extensions.inflater.LayoutInflaterExt.layoutInflater
import com.kotlin.extensions.view.ViewExt.clickable

/**
 *
 * @author why
 * @date 2025/3/8 21:09
 */
class TitleBarView(context: Context, attrs: AttributeSet?) :
    FrameLayout(context, attrs) {

    private val binding by lazy {
        LayoutTitleBarBinding.inflate(layoutInflater, this, false)
    }

    init {
        val typedArray = context.obtainStyledAttributes(attrs, R.styleable.TitleBarView)
        try {
            // 获取标题文本
            val titleText = typedArray.getString(R.styleable.TitleBarView_titleText)
            if (titleText != null) {
                setTitle(titleText)
            }

            // 获取标题文本资源 ID
            val titleTextRes = typedArray.getResourceId(R.styleable.TitleBarView_titleTextRes, 0)
            if (titleTextRes != 0) {
                setTitle(titleTextRes)
            }

            // 获取左侧图标资源 ID
            val leftIconRes = typedArray.getResourceId(R.styleable.TitleBarView_leftIconRes, 0)
            if (leftIconRes != 0) {
                setLeftIcon(leftIconRes)
            }

            // 是否启用关闭图标
            val closeIconEnabled = typedArray.getBoolean(R.styleable.TitleBarView_closeIconEnabled, false)
            if (closeIconEnabled) {
                setCloseIcon()
            }
        } finally {
            typedArray.recycle()
        }
        addView(binding.root)
        binding.ivLeft.clickable {
            safeFinishActivity()
        }
    }


    fun setTitle(title: String) {
        binding.tvTitle.text = title
    }

    fun setTitle(title: Int) {
        binding.tvTitle.text = resources.getString(title)
    }

    fun setLeftIcon(icon: Int, click: () -> Unit = {}) {
        binding.ivLeft.setImageResource(icon)
        binding.ivLeft.clickable {
            click.invoke()
        }
    }

    fun setCloseIcon(
        click: () -> Unit = {
            safeFinishActivity()
        }
    ) {
        binding.ivLeft.setImageResource(android.R.drawable.ic_menu_close_clear_cancel)
        binding.ivLeft.clickable {
            click.invoke()
        }
    }

    /**
     * 安全地获取 Activity 并调用其 finish 方法
     */
    fun safeFinishActivity() {
        val activity = getActivity()
        activity?.let {
            if (!it.isFinishing && !it.isDestroyed) {
                it.finish()
            }
        }
    }
}